<template>
  <div class="container">
    <div class="app-container">
      <department-edit ref="deptEdit" @addDept="getDepartmentsList" />
      <el-tree :data="depts" :props="defaultProps" :default-expand-all="true" :expand-on-click-node="false">
        <!-- 节点结构 -->
        <template v-slot="{data}">
          <el-row type="flex" justify="space-between" align="middle" style="width:100%;height:40px">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span style="margin:10px;display:inline-block;width:80px">{{ data.managerName }}</span>
              <el-dropdown @command="operateDept($event, data)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑子部门</el-dropdown-item>
                  <el-dropdown-item command="delete">删除部门</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>

          </el-row>
        </template>
      </el-tree>

    </div>
  </div>
</template>

<script>
import { getDepartment, deleteDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils/index'
import departmentEdit from './components/departmentEdit.vue'
export default {
  name: 'Department',
  components: { departmentEdit },
  data() {
    return {
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      deptEdit: ''
    }
  },
  created() {
    this.getDepartmentsList()
  },
  methods: {
    async getDepartmentsList() {
      const list = await getDepartment()
      console.log(list)
      this.depts = transListToTreeData(list, 0)
      // console.log(this.depts)
    },
    operateDept(type, data) {
      if (type === 'delete') {
        this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await deleteDepartment(data.id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getDepartmentsList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else { this.$refs.deptEdit.open(type, data) }
    }
  }

}
</script>

<style scoped>
.app-container {
  padding:30px 140px;
  font-size: 14px;
}

</style>
